<template>
    <div>
        <h1>登录页面</h1>
        <form @submit.prevent="login">
        <label for="username">账号:</label>
        <input type="text" id="username" v-model="username" required>
        <br>
        <label for="password">密码:</label>
        <input type="password" id="password" v-model="password" required>
        <br>
        <button type="submit">登录</button>
        </form>
        <p v-if="errorMessage" style="color: red;">{{ errorMessage }}</p>
    </div>
</template>

<script setup lang="ts">
    const username = ref('');
    const password = ref('');
    const errorMessage = ref('');
    const router = useRouter(); // 导入useRouter


    const login = async() => {
      if (username.value && password.value) {
        // 发起API请求 获取响应
        const {data, error} = await useFetch('/api/login', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: {
                username: username.value,
                password: password.value
            },
        });

        console.log(data, error);

        // 处理响应
        if (error.value) {
            errorMessage.value = '登录失败';
        } else {
            // 处理成功的登录逻辑
            const msg: string = data.value.msg;
            errorMessage.value = msg;
            // TODO 进行重定向
            router.push('/')
        }
        
      } else {
        // 错误提醒
        errorMessage.value = '请输入账号密码';
      }
    };

</script>